<template>
  <div>
    <!--    面包屑导航-->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
<!--    卡片视图-->
    <el-card>
<!--      添加按钮-->
      <el-row>
        <el-col>
          <el-button type="primary">添加角色</el-button>
        </el-col>
      </el-row>
<!--      列表视图-->
      <el-table :data="roleList" border stripe>g
        <el-table-column type="expand">
          <template v-slot="scope">
            <el-row :class="{'bdbottom':true,'bdtop': index1 ==0 ,'vcenter':true}" v-for="(item1,index1) in scope.row.children" :key="item1.id">
              <!--            一级权限-->
              <el-col :span="5">
                <el-tag closable @close="removeRightById(scope.row,item1.id)">
                  {{item1.authName}}
                </el-tag>
                <i class="el-icon-caret-right"/>
              </el-col>
              <!--            二级和三级权限-->
              <el-col :span="19">
<!--                通过for循环渲染二级-->
                <el-row v-for="(item2,index2) in item1.children" :key="item2.id" :class="{'bdtop':index2 != 0,'vcenter':true}">
                  <el-col :span="6">
                    <el-tag type="success" closable @close="removeRightById(scope.row,item2.id)">{{item2.authName}}</el-tag>
                    <i class="el-icon-caret-right"/>
                  </el-col>
                  <el-col :span="18">
                    <el-tag v-for="(item3) in item2.children" :key="item3.id" type="warning" closable @close="removeRightById(scope.row, item3.id)">
                      {{item3.authName}}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作" width="300px">
          <template v-slot="scope">
            <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row.id)">编辑</el-button>
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteById(scope.row.id)">删除</el-button>
            <el-button type="warning" icon="el-icon-setting" size="mini" @click="showSetRightDialog(scope.row)">分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!--编辑dialog-->
    <el-dialog title="修改角色" :visible.sync="editDialogVisible" width="30%" @close="editDialogClosed">
      <el-form :model="editForm" ref="editForm" label-width="70px">
        <el-form-item label="角色名" prop="username">
          <el-input v-model="editForm.roleName" ></el-input>
        </el-form-item>
        <el-form-item label="描述" prop="email">
          <el-input v-model="editForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer">
            <el-button @click="editDialogVisible = false" type="info">取消</el-button>
            <el-button @click="editRoleInfo" type="primary">确定</el-button>
          </span>
    </el-dialog>
<!--   分配权限的dialog-->
    <el-dialog title="分配权限" :visible.sync="setRightsVisible" width="50%" @close="setRightsClosed">
      <!--      树形控件-->
      <el-tree :data="rightsList" :props="treeProps" show-checkbox node-key="id" default-expand-all :default-checked-keys="defKeys" ref="treeRef"></el-tree>
      <span slot="footer">
        <el-button @click="setRightsVisible = false">取消</el-button>
        <el-button @click="allotRights" type="primary">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'Roles',
  data () {
    return {
      // 编辑form
      editForm: {},
      // 是否在编辑
      editDialogVisible: false,
      roleList: [],
      // 是否显示分配权限弹框
      setRightsVisible: false,
      // 权限列表
      rightsList: [],
      // 树形结构
      treeProps: {
        label: 'authName',
        children: 'children'
      },
      // 默认选定的key
      defKeys: [],
      // 当前的roleid
      roleId: ''
    }
  },
  created () {
    this.getRoleList()
  },
  methods: {
    async getRoleList () {
      const { data: result } = await this.$http.get('roles')
      if (result.meta.status !== 200) return this.$message.error('获取角色列表失败')
      this.roleList = result.data
    },
    // 编辑
    async showEditDialog (id) {
      // 根据id请求数据
      const { data: result } = await this.$http.get('roles/' + id)
      if (result.meta.status !== 200) return this.$message.error('请求角色失败')
      this.editForm = result.data
      this.editDialogVisible = true
    },
    // 关闭编辑框后重置内容
    editDialogClosed () {
      this.$refs.editForm.resetFields()
    },
    // 发起更改请求
    async editRoleInfo () {
      // 根据id修改角色
      const { data: result } = await this.$http.put('roles/' + this.editForm.roleId, {
        roleName: this.editForm.roleName,
        roleDesc: this.editForm.roleDesc
      })
      if (result.meta.status !== 200) return this.$message.error('修改失败')
      this.$message.success('修改成功')
      this.getRoleList()
      this.editDialogVisible = false
    },
    // 根据用户id删除角色
    async deleteById (id) {
      const confirmResult = await this.$confirm('确定永久删除该用户吗？', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (confirmResult !== 'confirm') return this.$message.info('已取消')
      // 请求数据
      const { data: result } = await this.$http.delete('roles/' + id)
      if (result.meta.status !== 200) return this.$message.error('删除失败')
      this.getRoleList()
      this.$message.success('删除成功')
    },
    // 根据用户id删除角色权限
    async removeRightById (role, rightId) {
      console.log('发起请求')
      const result = await this.$confirm('永久删除用户该权限？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (result !== 'confirm') return this.$message.info('已取消')
      // 发起请求
      const { data: res } = await this.$http.delete('roles/' + role.id + '/rights/' + rightId)
      if (res.meta.status !== 200) return this.$message.error('删除失败')
      this.$message.success('删除成功')
      role.children = res.data
    },
    // 给角色分配权限
    async showSetRightDialog (role) {
      this.roleId = role.id
      // 获取所有权限树
      const { data: result } = await this.$http.get('rights/tree')
      if (result.meta.status !== 200) return this.$message.error('获取权限列表失败')
      this.rightsList = result.data
      this.getLeafKeys(role, this.defKeys)
      this.setRightsVisible = true

      // console.log(this.rightsList)
    },
    // 通过递归，取出所有的三级权限放入defkeys中
    getLeafKeys (node, arr) {
      if (!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach(item => this.getLeafKeys(item, arr))
    },
    // 权限分配对话框关闭后，清除默认的节点
    setRightsClosed () {
      this.defKeys = []
    },
    // 发起分配权限请求
    async allotRights () {
      const keys = [
        // 展开数组放入
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      const idStr = keys.join(',')
      const { data: result } = await this.$http.post('roles/' + this.roleId + '/rights/', { rids: idStr })
      if (result.meta.status !== 200) return this.$message.error('添加失败')
      this.$message.success('添加成功')
      this.getRoleList()
      this.setRightsVisible = false
    }
  }
}
</script>

<style scoped>
.el-tag{
  margin: 7px
}
.bdtop{
  border-top: 1px solid #eee;
}
.bdbottom{
  border-bottom: 1px solid #eee;
}
.vcenter{
  display: flex;
  align-items: center;
}
</style>
